package com.njwb.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.njwb.json.ResponseResult;
import com.njwb.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

@RestController
public class UserController {
    @Autowired
    private RestTemplate restTemplate;
    //服务提供者的URL
    private String url = "http://127.0.0.1:7001/user";
    @PostMapping("user")
    public ResponseResult add(User user) throws JsonProcessingException {
        //封装表单数据
        MultiValueMap<String,String> params = new LinkedMultiValueMap<String,String>();
        //public interface MultiValueMap<K, V> extends Map<K, List<V>>
        //V:List<V>
        params.put("username", Arrays.asList(user.getUsername()));
        params.put("password",Arrays.asList(user.getPassword()));
        ResponseResult responseResult = restTemplate.postForObject(url, params, ResponseResult.class);
        return responseResult;
    }

    @GetMapping("user/{id}")
    public ResponseResult getById(@PathVariable("id") Integer id){
        return restTemplate.getForObject(url + "/{id}",ResponseResult.class,id);
    }

    @GetMapping("user")
    public ResponseResult findAll(){
        return restTemplate.getForObject(url,ResponseResult.class);
    }
    @DeleteMapping("user/{id}")
    public ResponseResult delById(@PathVariable("id") Integer id){
        //方法一、delete方法没有返回值，需要自己指定
//        restTemplate.delete(url + "/{id}",id);
//        return ResponseResult.success();
        //方法二、
        ResponseEntity<ResponseResult> responseEntity =
                restTemplate.exchange(url + "/{id}", HttpMethod.DELETE,null,ResponseResult.class,id);
        return responseEntity.getBody();
    }
    @PutMapping("user")
    public ResponseResult modify(User user){
        //和delete一样，put方法也没有返回值
        System.out.println(user);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String,String> params = new LinkedMultiValueMap<String,String>();
        params.put("id", Arrays.asList(user.getId().toString()));
        params.put("username", Arrays.asList(user.getUsername()));
        params.put("password",Arrays.asList(user.getPassword()));
        HttpEntity<MultiValueMap> httpEntity = new HttpEntity<MultiValueMap>(params,headers);
        ResponseEntity<ResponseResult>  responseEntity =
                restTemplate.exchange(url, HttpMethod.PUT,httpEntity,ResponseResult.class);
        return responseEntity.getBody();
    }
}
